from PIL import Image


def laplacian_sharpening_filter_rgb(image_path, output_path):
    """
    采用简单拉普拉斯算子形式对输入的RGB图像进行线性锐化滤波处理。

    参数:
    image_path (str): 输入图像的文件路径。
    output_path (str): 输出滤波后图像的文件路径。
    """
    # 打开原始图像
    image = Image.open(image_path)
    # 读取图像的尺寸
    width, height = image.size
    # 创建新的空白图像，尺寸与原图像相同，模式也相同，用于存储锐化后的图像
    new_image = Image.new(image.mode, (width, height))
    # 定义简单的拉普拉斯算子（3x3形式）
    laplacian_kernel = [[0, -1, 0],
                        [-1, 4, -1],
                        [0, -1, 0]]
    # 遍历图像的每个像素点（避开边缘部分）
    for y in range(1, height - 1):
        for x in range(1, width - 1):
            # 分别用于累计红、绿、蓝通道经过拉普拉斯算子处理后的像素值总和
            sum_red = 0
            sum_green = 0
            sum_blue = 0
            # 遍历拉普拉斯算子范围内的像素点
            for ky in range(3):
                for kx in range(3):
                    pixel = image.getpixel((x + kx - 1, y + ky - 1))
                    red, green, blue = pixel
                    sum_red += red * laplacian_kernel[ky][kx]
                    sum_green += green * laplacian_kernel[ky][kx]
                    sum_blue += blue * laplacian_kernel[ky][kx]
            # 获取原图像对应坐标的像素值
            original_pixel = image.getpixel((x, y))
            red_original, green_original, blue_original = original_pixel
            # 计算锐化后的像素值
            alpha = 1.5  # 锐化强度系数默认为1.5
            red_sharpened = int(red_original + alpha * sum_red)
            green_sharpened = int(green_original + alpha * sum_green)
            blue_sharpened = int(blue_original + alpha * sum_blue)
            # 限制像素值在0-255范围内
            red_sharpened = max(0, min(255, red_sharpened))
            green_sharpened = max(0, min(255, green_sharpened))
            blue_sharpened = max(0, min(255, blue_sharpened))
            # 将锐化后的像素值设置到新图像对应坐标位置
            new_image.putpixel((x, y), (red_sharpened, green_sharpened, blue_sharpened))
    # 保存锐化后的图像
    new_image.save(output_path)
    return new_image


image_path = "D:/cangku/computer-image-project-design/test.jpg"
output_path = "D:/cangku/computer-image-project-design/test1.jpg"
laplacian_sharpening_filter_rgb(image_path, output_path)